package com.ruoyi.common.web.config;

import com.ruoyi.common.core.config.RuoYiConfig;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.web.interceptor.FlexWebInvokeTimeInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 通用配置
 *
 * @author Lion Li
 */
@AutoConfiguration
public class ResourcesConfig implements WebMvcConfigurer
{

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 全局访问性能拦截
        registry.addInterceptor(new FlexWebInvokeTimeInterceptor());
    }

    @Value("${resourcefile:resourcefile}")
    private String resourcefile="resourcefile";

    @Value("${pathprefix:uploadFile}")
    private String pathprefix;
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /** 本地文件上传路径 */
        registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**")
            .addResourceLocations("file:" + RuoYiConfig.getProfile() + "/");

        //本地静态资源访问
        String file = "";
        if(System.getProperty("user.dir").contains(":")){
            //则时windos系统
            file="file:" + System.getProperty("user.dir") + "/" + resourcefile + "/";
        }else{
            file = "file:" + System.getProperty("user.dir")+ "/" + resourcefile + "/";
        }
        registry.addResourceHandler("/"+pathprefix+"/**")
            .addResourceLocations(file);
        System.out.println("配置的静态资源路径:");
        System.out.println(file);
        System.out.println("映射路径:/"+pathprefix+"/**");
    }

    /**
     * 跨域配置
     */
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        // 设置访问源地址
        config.addAllowedOriginPattern("*");
        // 设置访问源请求头
        config.addAllowedHeader("*");
        // 设置访问源请求方法
        config.addAllowedMethod("*");
        // 有效期 1800秒
        config.setMaxAge(1800L);
        // 添加映射路径，拦截一切请求
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        // 返回新的CorsFilter
        return new CorsFilter(source);
    }
}
